import { BaseModel } from '#/models/base';
import { generateEnumFromDict, getDictLabel, DICT_TYPE } from '#/utils/dict';

export namespace BOMApi {
  // BOM类型 - 使用字典
  export type BOMType = string;
  
  // BOM状态 - 使用字典
  export type BOMStatus = string;
  
  // 生命周期状态 - 使用字典
  export type LifecycleStatus = string;
  
  /**
   * 获取BOM类型选项
   */
  export async function getBomTypeOptions() {
    const { options } = await generateEnumFromDict(DICT_TYPE.BOM_TYPE);
    return options;
  }
  
  /**
   * 获取BOM状态选项
   */
  export async function getBomStatusOptions() {
    const { options } = await generateEnumFromDict(DICT_TYPE.BOM_STATUS);
    return options;
  }
  
  /**
   * 获取生命周期状态选项
   */
  export async function getLifecycleStatusOptions() {
    const { options } = await generateEnumFromDict(DICT_TYPE.LIFECYCLE_STATUS);
    return options;
  }
  
  /**
   * 获取BOM类型标签
   */
  export async function getBomTypeLabel(value: string) {
    return await getDictLabel(DICT_TYPE.BOM_TYPE, value);
  }
  
  /**
   * 获取BOM状态标签
   */
  export async function getBomStatusLabel(value: string) {
    return await getDictLabel(DICT_TYPE.BOM_STATUS, value);
  }
  
  /**
   * 获取生命周期状态标签
   */
  export async function getLifecycleStatusLabel(value: string) {
    return await getDictLabel(DICT_TYPE.LIFECYCLE_STATUS, value);
  }

  // 成本计算结果接口
  export interface CostCalculation {
    bom_id: number;
    bom_code: string;
    total_cost: number;
    material_cost: number;
    labor_cost: number;
    overhead_cost: number;
    calculation_date: string;
    breakdown?: {
      component_id: number;
      material_name: string;
      quantity: number;
      unit_cost: number;
      total_cost: number;
    }[];
  }

  // BOM状态变更参数接口
  export interface StatusChangeData {
    status: BOMStatus;
    reason?: string;
    effective_date?: string;
  }

  // BOM克隆参数接口
  export interface CloneBomData {
    new_bom_code: string;
    new_version?: string;
    copy_components?: boolean;
    copy_documents?: boolean;
  }

  // BOM组件批量添加参数接口
  export interface BatchAddComponentsData {
    bom_id: number;
    components: {
      material: number;
      quantity: number;
      unit: string;
      usage_rate?: number;
      scrap_rate?: number;
      sequence?: number;
      operation_code?: string;
      description?: string;
    }[];
  }

  // BOM组件批量更新参数接口
  export interface BatchUpdateComponentsData {
    components: {
      component_id: number;
      quantity?: number;
      usage_rate?: number;
      scrap_rate?: number;
      sequence?: number;
      operation_code?: string;
      description?: string;
    }[];
  }

  // BOM版本激活参数接口
  export interface ActivateVersionData {
    effective_date?: string;
    reason?: string;
  }

  // BOM文档查询参数接口
  export interface BomDocumentQueryParams {
    bom_id?: number;
    component_id?: number;
    document_type?: string;
  }

  // BOM主数据接口
  export interface BOM {
    bom_id?: number;
    bom_code: string;
    product: number;
    product_name?: string;
    product_sku?: string;
    bom_type: BOMType;
    bom_type_display?: string; // BOM类型显示文本
    version: string;
    current_version?: string;
    status: BOMStatus;
    status_display?: string; // 状态显示文本
    lifecycle_status: LifecycleStatus;
    lifecycle_status_display?: string; // 生命周期状态显示文本
    effective_date?: string;
    expiry_date?: string;
    is_active: boolean;
    description?: string;
    cost?: number;
    configuration_template?: any; // 用于CBOM
    routing_reference?: number; // 用于MBOM关联工艺路线
    components?: BOMComponent[]; // BOM组件列表
    created_by?: string;
    updated_by?: string;
    create_time?: string;
    update_time?: string;
    is_deleted?: boolean;
    remark?: string;
  }

  // BOM组件接口
  export interface BOMComponent {
    component_id?: number;
    bom: number;
    material: number;
    material_name?: string;
    material_sku?: string;
    quantity: number;
    unit: string;
    usage_rate: number;
    scrap_rate: number;
    sequence: number;
    unit_cost?: number;
    total_cost?: number;
    operation_code?: string;
    operation_name?: string;
    workstation?: string;
    lead_time?: number;
    preferred_supplier?: number;
    preferred_supplier_name?: string;
    supplier_part_number?: string;
    procurement_type?: string;
    quality_standard?: string;
    certification_requirements?: string;
    attributes?: any;
    description?: string;
    created_by?: string;
    updated_by?: string;
    create_time?: string;
    update_time?: string;
    is_deleted?: boolean;
    remark?: string;
  }

  // BOM版本接口
  export interface BOMVersion {
    version_id?: number;
    bom: number;
    version: string;
    status: string;
    status_display?: string;
    effective_date?: string;
    expiry_date?: string;
    is_active: boolean;
    description?: string;
    created_by?: string;
    updated_by?: string;
    create_time?: string;
    update_time?: string;
    is_deleted?: boolean;
    remark?: string;
  }

  // 替代物料接口
  export interface AlternativeMaterial {
    alt_material_id?: number;
    component: number;
    alternative_material: number;
    alternative_material_name?: string;
    substitution_ratio: number;
    is_active: boolean;
    approval_status: string;
    reason?: string;
    created_by?: string;
    updated_by?: string;
    create_time?: string;
    update_time?: string;
    is_deleted?: boolean;
    remark?: string;
  }

  // BOM文档接口
  export interface BOMDocument {
    document_id?: number;
    document_type: string;
    document_name: string;
    file_path: string;
    file_url?: string;
    version: string;
    description?: string;
    bom?: number;
    component?: number;
    created_by?: string;
    created_at?: string;
    updated_at?: string;
  }
}

/**
 * BOM模型类，用于与后端BOM API交互
 */
export class BOMModel extends BaseModel<BOMApi.BOM> {
  /**
   * 构造函数，设置基础URL
   */
  constructor() {
    super('/bom/');
  }

  /**
   * 计算BOM成本
   * @param bomId BOM ID
   * @returns 成本计算结果
   */
  calculateCost(bomId: number): Promise<BOMApi.CostCalculation> {
    return this.action('calculate-cost', {}, bomId, 'post');
  }

  /**
   * 更改BOM状态
   * @param bomId BOM ID
   * @param data 状态数据
   * @returns 更新结果
   */
  changeStatus(bomId: number, data: BOMApi.StatusChangeData): Promise<BOMApi.BOM> {
    return this.action('change-status', data, bomId, 'patch');
  }

  /**
   * 克隆BOM
   * @param bomId BOM ID
   * @param data 克隆参数
   * @returns 克隆的BOM
   */
  cloneBom(bomId: number, data: BOMApi.CloneBomData): Promise<BOMApi.BOM> {
    return this.action('clone', data, bomId, 'post');
  }

  /**
   * 导出BOM数据
   * @param bomId BOM ID
   * @returns 导出文件
   */
  exportBOM(bomId: number): Promise<Blob> {
    return this.action('export', {}, bomId, 'get', { responseType: 'blob' });
  }

  /**
   * 获取产品当前有效的BOM
   * @param productId 产品ID
   * @returns 当前有效的BOM
   */
  async getActiveBom(productId: number): Promise<BOMApi.BOM> {
    try {
      // 使用action方法调用特定的API端点
      const response = await this.action('active_bom', { product_id: productId }, null, 'get');
      
      // 检查响应是否是有效的BOM对象
      if (response && typeof response === 'object' && 'bom_id' in response) {
        return response as BOMApi.BOM;
      }
      
      throw new Error('未找到该产品的有效BOM');
    } catch (error) {
      throw new Error(`获取产品BOM失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }

  /**
   * 获取指定产品的所有BOM版本
   * @param productId 产品ID
   * @returns BOM版本列表
   */
  getProductBoms(productId: number): Promise<BOMApi.BOMVersion[]> {
    return this.action('product_boms', { product_id: productId }, null, 'get');
  }
}

/**
 * BOM组件模型类
 */
export class BOMComponentModel extends BaseModel<BOMApi.BOMComponent> {
  /**
   * 构造函数，设置基础URL
   */
  constructor() {
    super('/bom/components/');
  }

  /**
   * 批量添加BOM组件
   * @param bomId BOM ID
   * @param data 组件数据
   * @returns 添加结果
   */
  batchAddComponents(bomId: number, data: BOMApi.BatchAddComponentsData): Promise<BOMApi.BOMComponent[]> {
    return this.action('batch-add', { bom_id: bomId, components: data.components });
  }

  /**
   * 批量更新BOM组件
   * @param data 更新数据
   * @returns 更新结果
   */
  batchUpdateComponents(data: BOMApi.BatchUpdateComponentsData): Promise<BOMApi.BOMComponent[]> {
    return this.action('batch-update', data);
  }

  /**
   * 获取指定BOM的所有组件
   * @param bomId BOM ID
   * @returns 组件列表
   */
  async getBomComponents(bomId: number): Promise<BOMApi.BOMComponent[]> {
    try {
      // 使用action方法调用特定的API端点
      const response = await this.action('bom-components', { bom_id: bomId }, null, 'get');
      
      // 检查响应是否是有效的数组
      if (Array.isArray(response)) {
        return response as BOMApi.BOMComponent[];
      }
      
      // 如果响应是对象，可能包含数据字段
      if (response && typeof response === 'object' && 'data' in response && Array.isArray(response.data)) {
        return response.data as BOMApi.BOMComponent[];
      }
      
      throw new Error('获取BOM组件失败：返回数据格式不正确');
    } catch (error) {
      throw new Error(`获取BOM组件失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
}

/**
 * BOM版本模型类
 */
export class BOMVersionModel extends BaseModel<BOMApi.BOMVersion> {
  /**
   * 构造函数，设置基础URL
   */
  constructor() {
    super('/bom/versions/');
  }

  /**
   * 激活BOM版本
   * @param versionId 版本ID
   * @param data 激活参数
   * @returns 激活结果
   */
  activateVersion(versionId: number, data: BOMApi.ActivateVersionData): Promise<BOMApi.BOMVersion> {
    return this.action('activate', data, versionId, 'post');
  }

  /**
   * 获取指定BOM的所有版本
   * @param bomId BOM ID
   * @returns 版本列表
   */
  async getBomVersions(bomId: number): Promise<BOMApi.BOMVersion[]> {
    try {
      // 使用action方法调用特定的API端点
      const response = await this.action('bom-versions', { bom_id: bomId }, null, 'get');
      
      // 检查响应是否是有效的数组
      if (Array.isArray(response)) {
        return response as BOMApi.BOMVersion[];
      }
      
      // 如果响应是对象，可能包含数据字段
      if (response && typeof response === 'object' && 'data' in response && Array.isArray(response.data)) {
        return response.data as BOMApi.BOMVersion[];
      }
      
      throw new Error('获取BOM版本失败：返回数据格式不正确');
    } catch (error) {
      throw new Error(`获取BOM版本失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
}

/**
 * 替代物料模型类
 */
export class AlternativeMaterialModel extends BaseModel<BOMApi.AlternativeMaterial> {
  /**
   * 构造函数，设置基础URL
   */
  constructor() {
    super('/bom/alternatives/');
  }

  /**
   * 获取指定组件的所有替代物料
   * @param componentId 组件ID
   * @returns 替代物料列表
   */
  async getComponentAlternatives(componentId: number): Promise<BOMApi.AlternativeMaterial[]> {
    try {
      // 使用action方法调用特定的API端点
      const response = await this.action('component-alternatives', { component_id: componentId }, null, 'get');
      
      // 检查响应是否是有效的数组
      if (Array.isArray(response)) {
        return response as BOMApi.AlternativeMaterial[];
      }
      
      // 如果响应是对象，可能包含数据字段
      if (response && typeof response === 'object' && 'data' in response && Array.isArray(response.data)) {
        return response.data as BOMApi.AlternativeMaterial[];
      }
      
      throw new Error('获取替代物料失败：返回数据格式不正确');
    } catch (error) {
      throw new Error(`获取替代物料失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
}

/**
 * BOM文档模型类
 */
export class BOMDocumentModel extends BaseModel<BOMApi.BOMDocument> {
  /**
   * 构造函数，设置基础URL
   */
  constructor() {
    super('/bom/documents/');
  }

  /**
   * 获取指定BOM或组件的所有文档
   * @param params 查询参数
   * @returns 文档列表
   */
  async getBomDocuments(params: BOMApi.BomDocumentQueryParams): Promise<BOMApi.BOMDocument[]> {
    try {
      // 使用action方法调用特定的API端点
      const response = await this.action('bom-documents', params, null, 'get');
      
      // 检查响应是否是有效的数组
      if (Array.isArray(response)) {
        return response as BOMApi.BOMDocument[];
      }
      
      // 如果响应是对象，可能包含数据字段
      if (response && typeof response === 'object' && 'data' in response && Array.isArray(response.data)) {
        return response.data as BOMApi.BOMDocument[];
      }
      
      throw new Error('获取BOM文档失败：返回数据格式不正确');
    } catch (error) {
      throw new Error(`获取BOM文档失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }

  /**
   * 上传BOM文档
   * @param data 文档数据
   * @returns 上传结果
   */
  uploadDocument(data: FormData): Promise<BOMApi.BOMDocument> {
    return this.action('upload', data, null, 'post');
  }
}
